package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @projectName: server-day0718-pay
 * @package: com.bwie.filter
 * @className: GlobalFilter
 * @author: 陈彤彤
 * @description: TODO
 * @date: 2025/7/18 20:47
 * @version: 1.0
 */
@Configuration
public class GlobalFilter implements org.springframework.cloud.gateway.filter.GlobalFilter {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /*获取参数*/
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        /*获取请求参数*/
        String url = request.getURI().getPath();
        System.out.println("请求参数为：" + url);

        /*白名单*/
        if (url.contains("/sendPhoneCode") || url.contains("/phoneLogin") || url.contains("/userReg")){
            System.out.println("登录接口：" + url);
            return chain.filter(exchange);
        }

        /*判断token是否为空*/
        //获取token
        String token = request.getHeaders().getFirst("token");
        if (token == null || token.isEmpty()){
            System.out.println("token为空:" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        /*判断token是否过期*/
        //解析token
        Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = claims.get("userId", Integer.class);
        //获取redisKey
        String redisKey = "token-" + userId;
        String redisToken = redisTemplate.opsForValue().get(redisKey);
        if (redisToken == null || redisToken.isEmpty()){
            System.out.println("token过期：" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        /*比较两个token*/
        if (!token.equals(redisToken)){
            System.out.println("token错误：" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        /*token续期*/
        redisTemplate.expire(redisKey,60, TimeUnit.MINUTES);

        /*放行*/
        System.out.println("放行：" + url);
        return chain.filter(exchange);
    }
}
